/**
 * 使用示例 <div v-permission="'add_user'"/>
 */

import Vue from 'vue';

// 接口地址
var _URL = function() {
    if ( location.host.indexOf('.itaojindev.cn') > -1 ) {
        return "//127.0.0.1:40010/api/";
    }

    if ( location.host.indexOf('.itaojintest.cn') > -1 ) {
        return "//sso.itaojintest.cn/api/";
    }

    return "//sso.itaojin.cn/api/";
};

// 判断是否有此权限
var _hasPermission = function(_this, _permissions) {
    for ( var j=0; j < _permissions.length; j++ ) {
        // 功能权限
        if ( _permissions[j].name == _this.binding.value ) {
            return true;
        }

        // 资源权限
        if ( _this.group + ":" + _permissions[j].name == _this.binding.value ) {
            return true;
        }
    }

    // console.log('#27 not _hasPermission', _this, _permissions)
    return false;
};

// 显示
var _visibleIfShould = function( _this, _permissions) {
    if ( "permission" == _this.name ) {
        if ( _hasPermission( _this, _permissions) ) {
            _this.el.style.visibility = 'visible'; // 有权限就显示
        }

        return;
    }

    if ( "noPermission" == _this.name ) {
        if ( !_hasPermission( _this, _permissions) ) {
            _this.el.style.visibility = 'visible'; // 无权限就显示
        }

        return;
    }

    console.log('#52 _visibleIfShould, _this.binding.name=', _this.binding.name, _this);
};

// 分组
var _groupMap = function() {
    var groupMap = {};

    // 分组
    for ( var i=0; i < window.PermissionList.length; i++ ) {
        var group = window.PermissionList[i].group;

        if ( !group ) {
            continue;
        }

        if ( !groupMap[group] ) {
            groupMap[group] = [];
        }

        groupMap[group].push(window.PermissionList[i]);
    }

    return groupMap;
};

var _listByAppKeyAndResourceAndAccountId = function(_resourceType, _resourceId, groupMap, key) {
    $.ajax({
        url : _URL() + "PermissionApi.listByAppKeyAndResourceAndAccountId",
        data : {
            appKey : Vue.config.permissionAppKey,
            resourceType : _resourceType,
            resourceId : _resourceId,
            accountId : Vue.config.permissionAccountId,
            accountToken : Vue.config.permissionAccountToken
        }
    }).done(function(res) {
        for ( var i=0; i < groupMap[key].length; i++ ) {
            _visibleIfShould(groupMap[key][i], res.result);
        }
    });
};

var _listByAppKeyAndAccountId = function(group_0) {
    $.ajax({
        url : _URL() + "PermissionApi.listByAppKeyAndAccountId",
        data : {
            accountId : Vue.config.permissionAccountId,,
            accountToken : Vue.config.permissionAccountToken
            appKey : Vue.config.permissionAppKey
        }
    }).done(function(res) {
        for ( var i=0; i < group_0.length; i++ ) {
            _visibleIfShould(group_0[i], res.result);
        }
    });
};

// 请求权限数据
var _loadData = function() {
    // 功能权限，不涉及资源
    var group_0 = window.PermissionList.filter( e => { return !e.group; } );
    _listByAppKeyAndAccountId(group_0);

    // 资源权限
    var groupMap = _groupMap();

    // 每组请求权限
    for ( var key in groupMap ) {
        var j = key.indexOf(":");
        var _resourceType = key.substring( 0, j );
        var _resourceId = key.substring( j + 1 );

        _listByAppKeyAndResourceAndAccountId(_resourceType, _resourceId, groupMap, key);
    }
};

// 添加到集合
var _pushToList = function (e) {
    var p = e.binding.value;
    if ( !p ) {
        console.log('#134 error, e=', e);
        return;
    }

    var i = p.lastIndexOf(":");
    if ( i > 0 ) {
        e.group = p.substring(0, i);
    }

    e.name = e.binding.name;
    window.PermissionList.push(e);
};

// 指令
var _onDirectiveBind = function(el, binding, vnode) {
    el.style.visibility = 'hidden'; // 先隐藏按钮

    // 集合后批量请求
    if ( !window.PermissionList ) {
        window.PermissionList = [];
    }

    // 添加到集合
    _pushToList({ el : el, binding : binding, vnode : vnode });

    clearTimeout(window.PermissionTimeoutId);
    window.PermissionTimeoutId = setTimeout(_loadData, 100);
};

// VUE 指令
var _permission_directive = {
    bind : _onDirectiveBind
};

var _account_directive = {
    bind : function(el, binding, vnode) {
        $.ajax({
            url : _URL() + "AccountApi.findAccountById_2",
            data : {
                id : Vue.config.permissionAccountId,
                accountToken : Vue.config.permissionAccountToken
            }
        }).done(function(res) {
            el.innerText = "\naccount\n" + JSON.stringify(res.result) + "\n\n";
        });
    }
};

var _roles_directive = {
    bind : function(el, binding, vnode) {
        $.ajax({
            url : _URL() + "RoleApi.listByAccountId",
            data : {
                accountId : Vue.config.permissionAccountId,
                accountToken : Vue.config.permissionAccountToken
            }
        }).done(function(res) {
            el.innerText = "\nroles\n" + JSON.stringify(res.result) + "\n\n";
        });
    }
};

var _permissions_directive = {
    bind : function(el, binding, vnode) {
        $.ajax({
            url : _URL() + "PermissionApi.listByAccountId",
            data : {
                accountId : Vue.config.permissionAccountId,
                accountToken : Vue.config.permissionAccountToken
            }
        }).done(function(res) {
            el.innerText = "\npermissions\n" + JSON.stringify(res.result) + "\n\n";
        });
    }
};

// 注册指令。有指定权限才显示
Vue.directive('permission', _permission_directive);
// 简写的别名
Vue.directive('perm', _permission_directive);
// 简写的别名
Vue.directive('has', _permission_directive);

// 没有指定权限时显示
Vue.directive('noPermission', _permission_directive);
Vue.directive('no', _permission_directive);

// 显示我的用户信息
Vue.directive('account', _account_directive);

// 显示我的角色信息
Vue.directive('roles', _roles_directive);

// 显示我的权限信息
Vue.directive('permissions', _permissions_directive);